package com.linln.modules.area.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linln.modules.area.domain.Area;
import com.linln.modules.area.repository.AreaMapper;
import com.linln.modules.area.service.AreaService;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.modules.area.service.impl
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.modules.area.service.impl
 * @Description: TODO
 * @date Date : 2020年11月30日 14:53
 */

@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

    @Autowired
    private AreaMapper areaMapper;

    @Override
    @Cacheable("cityArea")
    public Map<String, List<Area>> getAreaGroupByInitials(String keyword) {
        return groupByInitials(areaMapper.selectAllAreaCity(keyword));
    }

    @Cacheable(cacheNames = "area/getAreaByName")
    @Override
    public Area getAreaByName(String name) {
        return areaMapper.selectAreaByName(name);
    }

    @Cacheable(cacheNames = "area/getSonIds")
    @Override
    public List<Integer> getSonIds(Integer areaId) {
        if (areaId != null) {
            List<Integer> integers = areaMapper.selectSonIds(areaId);
            integers.add(areaId);
            return integers;
        }
        return null;
    }

    private Map<String, List<Area>> groupByInitials(List<Area> areaList) {
        Map<String, List<Area>> map = new HashMap<>();
        areaList.forEach(item -> {
            if (map.containsKey(item.getPerPinYin())) {
                List<Area> list = map.get(item.getPerPinYin());
                list.add(item);
            } else {
                List<Area> list = new ArrayList<>();
                list.add(item);
                map.put(item.getPerPinYin(), list);
            }
        });
        return map;
    }

}
